package com.quanyan.operative.mq.Consumer;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;

import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.operative.model.resp.TbUserInfo;
import com.quanyan.operative.service.TbUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

import javax.annotation.PostConstruct;

/**
 * Created by Administrator on 2016/7/15.
 */
@Component("mqUserSettingConsumer")
public class MqUserSettingConsumer extends AbstractMqConsumer {

    private static final Logger logger = LoggerFactory.getLogger(MqUserSettingConsumer.class);

    private static final String GROUP = "USER_SETTING_CONSUMER_GROUP";
    private static final String INSTANCE = "USER_SETTING_CONSUMER_INSTANCE";

    @Value("${mq.nameServer.address}")
    private String nameServerAddress;

    @Autowired
    private TbUserInfoService tbUserInfoService;

    @PostConstruct
    void run() {
        logger.info("用户设置mq消费--消息启动{}",nameServerAddress);
        super.start();
    }

    @Override
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        logger.info("用户设置开始---------------------------------》接收消息");
        //处理自身业务逻辑
        MessageExt messageExt = messages.get(0);
        //处理用户任务消息。。
        if (TbUserInfoService.topic.equals(messageExt.getTopic()) && TbUserInfoService.tag.equals(messageExt.getTags())) {
            byte[] bodyByte = messageExt.getBody();
            String msgId = messageExt.getMsgId();//mq内部id
            logger.info("mq消息id:{},业务key :{}",msgId,messageExt.getKeys());
            TbUserInfo tbUserInfo = (TbUserInfo)ObjectUtil.toObject(bodyByte);
            tbUserInfoService.updateSetting(tbUserInfo.getId(),null,1,1);
        }
        logger.info("用户设置结束---------------------------------》接收消息");
        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

    @Override
    protected String getConsumerGroup() {
        return this.GROUP;
    }

    @Override
    protected String getNameServerAddress() {
        return this.nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return this.INSTANCE;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(TbUserInfoService.topic, TbUserInfoService.tag); //订阅用户做任务的topic与tag
        return mqTopics;
    }
}
